'use strict';
/**
 * Created by FreezeSoul on 2015/10/23.
 */
define([
        'jquery',
        'underscore',
        'loglevel',
        'json!app/plugins/config.json',

        'app/core/util',

        'svgjs',
        'raphael',

        'velocity',
        'velocityUi',

        /*一些常用的效果库*/
        'css!libs/cssgram/source/css/cssgram.min.css',
        'css!libs/animate.css/animate.min.css',
        'css!libs/hover/css/hover-min.css'
    ],
    function ($, _, log, config, Util) {

        var option = {
            rootPath: 'app/plugins/',
            configFile: 'manifest.json'
        };

        function initManifests() {
            var promises = [];
            _.each(config.controls, function (ctype) {
                _.each(ctype.controls, function (c) {
                    var d = new $.Deferred();
                    var path = option.rootPath + c.path + "/" + option.configFile + "?m=" + config.version;
                    require(['json!' + path], function (manifest) {
                        manifest.path = c.path;
                        manifest.type = ctype.type;
                        manifest.rootPath = option.rootPath;
                        d.resolve(manifest);
                    });
                    promises.push(d);
                });
            });
            return $.when.apply($, promises).promise();
        }

        function loadPluginModule(name) {
            var d = new $.Deferred();
            initManifests().then(function () {
                log.info("loadPluginModule:" + name);
                var module = _.find(arguments, function (manifest) {
                    return manifest.uid === name;
                });
                if(module){
                    var path = module.rootPath + module.path + "/" + module.bootstrap + "?p=" + module.version;
                    require([path], function (bootstrap) {
                        //返回值：插件类，模块配置
                        d.resolve(bootstrap, module);
                    });
                }else{
                    log.error("Module load failed:" + name);
                    d.reject();
                }
            });
            return d.promise();
        }

        Util.accreditCheck();

        return {
            initManifests: initManifests,
            loadPluginModule: loadPluginModule
        }
    });